package de.busschedule.control;

import java.util.HashMap;
import java.util.Map;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import de.busschedule.R;
import de.busschedule.entities.BusLine;
import de.busschedule.logging.Logger;

public class GoogleMapHandler{
	private final String TAG = "GoogleMapHandler";
	
	public GoogleMapHandler(){}
	
	public void addMarkers(GoogleMap map, DBHandler handler, BusLine line, boolean all){
		Map<String, String> stopsGPS = new HashMap<String, String>();
		if(all){
			stopsGPS = handler.getAllStopsGPS();
		}else{
			stopsGPS = handler.getStopsGPS(line);				
		}
		
		for(Map.Entry<String, String> entry : stopsGPS.entrySet()){
			if((entry.getValue() != null) && (!entry.getValue().equals(""))){
				String str = entry.getValue();
				if(!str.equals("")){					
					String[] nameAndGPS = str.split(AppConstants.delimiter);
					//If gps exists
					if(nameAndGPS.length > 1){
						String[] gps = nameAndGPS[1].split(AppConstants.gpsdelimiter);
						// create markers
						for(int i = 0; i < gps.length; i += 2){
							try{
								MarkerOptions marker = new MarkerOptions().position(
									new LatLng(Double.parseDouble(gps[i]), Double
											.parseDouble(gps[i + 1]))).title(nameAndGPS[0]);
								// change marker icon
								marker.icon(BitmapDescriptorFactory
										.fromResource(R.drawable.busstop_sign_small));
								// Center the marker
								marker.anchor(0.5f, 0.5f);
								// add marker
								map.addMarker(marker);
							}catch(NumberFormatException e){
								Logger.error(TAG, "Cannot cast " + gps[i] + " or " + gps[i+1] + " to double!");
							}
						}
					}
				}
			}
		}
	}
	
	public void removeMarkers(GoogleMap map){
		map.clear();
	}
}
